/**
 * 用户状态管理
 * 使用Pinia进行用户状态管理
 */

import { defineStore } from 'pinia'
import storage, { STORAGE_KEYS } from '@/utils/storage.js'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: null,
    token: null,
    
    // 学习统计
    learningStats: {
      totalCourses: 0,
      totalHours: 0,
      totalPoints: 0,
      checkinDays: 0,
      certificates: 0
    },
    
    // 用户设置
    preferences: {
      theme: 'light',
      language: 'zh-CN',
      notifications: true,
      autoPlay: false
    },
    
    // 缓存数据
    cache: {
      myCourses: [],
      myExams: [],
      searchHistory: []
    }
  }),

  getters: {
    // 是否已登录
    isLoggedIn: (state) => !!state.token,
    
    // 获取用户ID
    userId: (state) => state.userInfo?.id || null,
    
    // 获取用户名
    userName: (state) => state.userInfo?.name || '未登录',
    
    // 获取用户头像
    userAvatar: (state) => state.userInfo?.avatar || '/static/default-avatar.png',
    
    // 获取用户等级
    userLevel: (state) => state.userInfo?.level || '普通学员',
    
    // 是否VIP
    isVip: (state) => state.userInfo?.isVip || false,
    
    // 获取学习进度
    learningProgress: (state) => {
      return {
        courses: state.learningStats.totalCourses,
        hours: state.learningStats.totalHours,
        points: state.learningStats.totalPoints,
        certificates: state.learningStats.certificates
      }
    }
  },

  actions: {
    /**
     * 设置用户信息
     * @param {Object} userInfo - 用户信息
     */
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      storage.set(STORAGE_KEYS.USER_INFO, userInfo)
    },

    /**
     * 设置Token
     * @param {string} token - 用户Token
     */
    setToken(token) {
      this.token = token
      storage.set(STORAGE_KEYS.TOKEN, token)
    },

    /**
     * 设置用户偏好
     * @param {Object} preferences - 用户偏好设置
     */
    setPreferences(preferences) {
      this.preferences = { ...this.preferences, ...preferences }
      storage.set(STORAGE_KEYS.USER_PREFERENCES, this.preferences)
    },

    /**
     * 更新学习统计
     * @param {Object} stats - 学习统计数据
     */
    updateLearningStats(stats) {
      this.learningStats = { ...this.learningStats, ...stats }
      storage.set('learning_stats', this.learningStats)
    },

    /**
     * 添加搜索历史
     * @param {string} keyword - 搜索关键词
     */
    addSearchHistory(keyword) {
      if (!keyword.trim()) return
      
      const history = this.cache.searchHistory.filter(item => item !== keyword)
      history.unshift(keyword)
      
      // 限制历史记录数量
      if (history.length > 10) {
        history.splice(10)
      }
      
      this.cache.searchHistory = history
      storage.set(STORAGE_KEYS.SEARCH_HISTORY, history)
    },

    /**
     * 清空搜索历史
     */
    clearSearchHistory() {
      this.cache.searchHistory = []
      storage.remove(STORAGE_KEYS.SEARCH_HISTORY)
    },

    /**
     * 添加我的课程
     * @param {Object} course - 课程信息
     */
    addMyCourse(course) {
      const exists = this.cache.myCourses.find(item => item.id === course.id)
      if (!exists) {
        this.cache.myCourses.unshift(course)
        storage.set(STORAGE_KEYS.MY_COURSES, this.cache.myCourses)
      }
    },

    /**
     * 移除我的课程
     * @param {number} courseId - 课程ID
     */
    removeMyCourse(courseId) {
      this.cache.myCourses = this.cache.myCourses.filter(item => item.id !== courseId)
      storage.set(STORAGE_KEYS.MY_COURSES, this.cache.myCourses)
    },

    /**
     * 添加我的考试
     * @param {Object} exam - 考试信息
     */
    addMyExam(exam) {
      const exists = this.cache.myExams.find(item => item.id === exam.id)
      if (!exists) {
        this.cache.myExams.unshift(exam)
        storage.set(STORAGE_KEYS.MY_EXAMS, this.cache.myExams)
      }
    },

    /**
     * 更新用户信息
     * @param {Object} updates - 更新字段
     */
    updateUserInfo(updates) {
      if (this.userInfo) {
        this.userInfo = { ...this.userInfo, ...updates }
        storage.set(STORAGE_KEYS.USER_INFO, this.userInfo)
      }
    },

    /**
     * 签到
     */
    checkIn() {
      this.learningStats.checkinDays += 1
      this.learningStats.totalPoints += 10
      
      storage.set('learning_stats', this.learningStats)
      
      uni.showToast({
        title: '签到成功 +10积分',
        icon: 'success'
      })
    },

    /**
     * 登录
     * @param {Object} loginData - 登录数据
     */
    async login(loginData) {
      try {
        // 这里调用登录API
        const response = await this.$api.user.login(loginData)
        
        if (response.code === 200) {
          this.setToken(response.data.token)
          this.setUserInfo(response.data.user)
          
          // 加载用户相关数据
          await this.loadUserData()
          
          return { success: true, data: response.data }
        } else {
          return { success: false, message: response.message }
        }
      } catch (error) {
        console.error('Login error:', error)
        return { success: false, message: '登录失败，请重试' }
      }
    },

    /**
     * 登出
     */
    async logout() {
      try {
        // 调用登出API
        await this.$api.user.logout()
      } catch (error) {
        console.error('Logout error:', error)
      }
      
      // 清空本地数据
      this.userInfo = null
      this.token = null
      this.cache.myCourses = []
      this.cache.myExams = []
      
      // 清除存储
      storage.remove(STORAGE_KEYS.TOKEN)
      storage.remove(STORAGE_KEYS.USER_INFO)
      storage.remove(STORAGE_KEYS.MY_COURSES)
      storage.remove(STORAGE_KEYS.MY_EXAMS)
      
      uni.reLaunch({
        url: '/pages/login/index'
      })
    },

    /**
     * 加载用户数据
     */
    async loadUserData() {
      try {
        // 从存储加载数据
        this.userInfo = storage.get(STORAGE_KEYS.USER_INFO)
        this.token = storage.get(STORAGE_KEYS.TOKEN)
        this.preferences = storage.get(STORAGE_KEYS.USER_PREFERENCES) || this.preferences
        this.learningStats = storage.get('learning_stats') || this.learningStats
        this.cache.myCourses = storage.get(STORAGE_KEYS.MY_COURSES) || []
        this.cache.myExams = storage.get(STORAGE_KEYS.MY_EXAMS) || []
        this.cache.searchHistory = storage.get(STORAGE_KEYS.SEARCH_HISTORY) || []
        
        if (this.token) {
          // 从服务器获取最新数据
          const [userInfoRes, statsRes] = await Promise.all([
            this.$api.user.getUserInfo(),
            this.$api.user.getLearningStats()
          ])
          
          if (userInfoRes.code === 200) {
            this.setUserInfo(userInfoRes.data)
          }
          
          if (statsRes.code === 200) {
            this.updateLearningStats(statsRes.data)
          }
        }
      } catch (error) {
        console.error('Load user data error:', error)
      }
    },

    /**
     * 初始化用户状态
     */
    async init() {
      await this.loadUserData()
    }
  }
})

export default useUserStore